from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import os
from model.User import getUserByUsername, createUser
from model.Auction import createAuction
from model.Project import createProject
import appengine_utilities.sessions
from model.Bid import createBid
from google.appengine.ext import db
from model.Entry import createEntry
from util import AuthorizedPage
from model.User import User


class NetworkPage(AuthorizedPage):
    
    def getIfAuthorized(self):
        filter = self.request.get('filter')
        error = self.request.get('error')
        
        messages = {"duplicate_name" : "Tag already exists!",
                    "no_tag" : "Tag does not exist!"}
        if error not in messages.keys():
            error = ""
        else:
            error = messages[error]
        
        
        template_values = {"filter" : filter, "error" : error, "tags" : self.authorizedUser.tag_list}
        
        all_users = User.all()
        
        tagged_users = {}
        if filter != "":
            taggings = self.authorizedUser.getTaggings()
            displayed_users = []
            
            for tagging in taggings:
                for tag in tagging.tags:
                    if tag == filter:
                        displayed_users.append(tagging.tagged_user)
                        tagged_users[tagging.tagged_user.username] = tagging.tags 
                        break
                    
            
            all_users = displayed_users
        
        else:
            for tagging in self.authorizedUser.getTaggings():
                tagged_users[tagging.tagged_user.username] = tagging.tags
        
        
        displayed_users = []
        for user in all_users:
            tags = []
            if tagged_users.has_key(user.username):
                tags = tagged_users[user.username]
            
            displayed_users.append({"name" : user.name,
                                    "username" : user.username,
                                    "gender" : user.gender,
                                    "age" : user.age,
                                    "tags" : tags,
                                    "city" : user.city})
            
        
        template_values["users"] = displayed_users
        
        self.outputHeader()
        
        path = os.path.join(os.path.dirname(__file__), 'network.html')
        self.response.out.write(template.render(path, template_values))        



